package com.itheima.reggin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggin.entity.Orders;
import com.itheima.reggin.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 支付功能
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private OrdersService ordersService;
    //APP_ID
    private final String APP_ID = "2021000121612042";
    //应用私钥:
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCRR3AhWfqUO60D8D8lCRQbzqwfX/gz6get0283OMnOsT1pl8r3EKIGLCtBLz+z/xeO/1UBzE/n/i7MJWlrdIXtLMbGEReqjbj7eN5JNIs3hKSk8dXyK/3/azf79Z15NXyPbwdX6dK+Pbcgzs+qN5UvAoBNsQJQZaxmKru//Xzwta6DmDSfrqrV+QdoNqp8tOoacIgLo2KDePnEkopvfIB24m4kcsReo0NPOCMbGYCa6GkDzpeHt7Qtn4396cPgnUV3a/eSyfAAI+XNefob2NtgnDIFMLkxUKdf7BOa1BDLuuKkpg1Y0KnAu0ZJcYo6bR9uIRs2Jk8+E6ToNaRbP9wZAgMBAAECggEAAJSuiBOaAtmyOV/OgNFmeS38VivGDD8VRMahnTDm7aKbwj5PG2m/nBK1IY+Uy51rdLDkoBs2/pBvk3Va1Ikkt+wD52rOE2p5oNe828IQBGrNVbN5zXwLiefd024J8SAbnV8uQlW29/e7MbBh+CY8vHFgHe9lOPkPFWF6WqwiwbuWqgyOTKz6+PYgB0Zxg349jGvXB+JA6VbYDEQ52Iuty+vssy+6LzBExlASboFr7I0Q5DA/L8ba9RUg7BbTrRZWCnZ1F9RHP0Ffs/HRfFikYUXEoZhnQ0xyDrEONJsiNJA5HdHUD1dyxJSeNbm2s9upXPbaQwuSVzWxMNekk2WwOQKBgQDHeYsyikxAXsrjf6YsZz4rD2Y2mMhX4dfPMtODIozscNYMnOq3KJ45/AoZ16DVfKwwvcQLfpISHaLpCNibHwX2hY2ddnBNHrz1RycdXfQVnX0Z1Ci1Nxu2hyTrneQiiApGDvKQarlwgSY5qK8o93QfyTLJ0n7y5+Wx9OMC8vFpzwKBgQC6cmKm/K75Lc1q2HhFeV5HMMSAnowYtWkX5YJWqzOkDC7zAjp/nSZLMxXbwK73W81gFgc/zIagK0L9qRk0kLlhtM0yvymvD7I3irMss/9r89Tt0jgILU0FO1rMeLKOzgT0e1+TPL05OF2POULwViipDErr3u5P2RQnMQrkycIdlwKBgBvdc798qEg5tbfwBgOf7IRRY2LvFtWH/AC6xedEtVD2NkCOzw8FAo1xEuwnPhV0lA0/BRrh9H/JWg+Zp8CLpeaZI35CpE9xos3UwbcNf+JhHK+1/nXKG/n0iQjNBqh4Po8o2WOpNPxtXiyhzs43OyaRkaG14PwHvwOMBQZNb8HrAoGAQgE2nYk85GfrndSul2HFF4zTM/ls/V5TqysL/mSzbnMFt+/lB8J5iQu3xEktZ9JvHYIO5O4iBtfp6mUP0EUf69AXCM0WE6yJ2hHXJo8+cFgs3Ficj4CCEMUXeuWLyPR0WpzGlBhfoL8smASchvrpgBci+ue8FDZ0ZP9+rMokV1cCgYEAwZ88+2caNAsm2BaGmd/CD8mTRi9+sgHEBz5lbgcgfluEWnH9Oy83rT4gRq7coGWmjvtk3xTQK8dCizt0/sqnPhlPnIWP5UEd/lww+oHRfY347NVzYiN3U3rH6wXudcI5Qp2lPmCz9XoeE5diYxwHUPECArcGxcY1WCSmzbhA1SE=";
    //防止中文乱码
    private final String CHARSET = "UTF-8";
    //支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsr7P1bqdj/r2Q+fNjNI9KxRnQgRtwsqu1kUYBPXp2Ji4/yLl3tyog94pqpIYj40dEBMDaPVuvLxA6HwjP86p03l2jfEzZzh4ny3MiymVeZiz6ToX2Qondr2UyQjIMJIRQDKZyzeddYeUtDrHymj4d/A5r7TSy4Okaj+9NyhGEAUA0iMWaLyqGqAantJE4bjDMfZ6WpPs2Z8PFcxNN39hSTkhECwuOrKNI08VGAXOw0SYI8BrafWxrLQXN6C+JBKIevP+CuCQP8Lx9DfjbcWsN+43gP4xNk7SlyN7wWt3GHoiYG3o7/FX2bpm88w4f6REcuNioifaaSygK65H+8UAHwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    //数据类型json
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
//    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost/front/page/pay-success.html";



    @RequestMapping("/pay")
    public void alipay(HttpServletResponse httpResponse, HttpSession session, Long orderId) throws IOException, AlipayApiException {
        // HttpSession session:修改submit,使用session域功能,获取订单id
        if (orderId == null) {
            // 获取订单编号,此为long类型的.从session域
            orderId = (Long) session.getAttribute("orderId");
        }

        //条件构造器,
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //比对订单信息,订单信息一致,获取一个orders对象
        queryWrapper.eq(Orders::getNumber,  String.valueOf(orderId));
        Orders orders = ordersService.getOne(queryWrapper);

        AlipayClient alipayClient = new DefaultAlipayClient( //默认支付宝客户端
                //调用静态成员变量
                GATEWAY_URL,
                APP_ID, APP_PRIVATE_KEY,
                FORMAT, CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();//支付宝 Trade Wap 支付请求

        request.setReturnUrl(RETURN_URL);
        JSONObject bizContent = new JSONObject();//商务内容返回的是
        bizContent.put("out_trade_no", String.valueOf(orderId));//订单id
        bizContent.put("total_amount", orders.getAmount());//总的金额
        bizContent.put("subject", "黄帅外卖");//类型
        bizContent.put("product_code", "QUICK_WAP_WAY");

        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        String form = response.getBody();
        httpResponse.setContentType("text/html;charset=UTF-8");
        httpResponse.getWriter().write(form);
    }


    /**
     * 去支付
     * @param orderId
     * @return
     */
    @RequestMapping()
    public String gotoPay(Long orderId) {

        //1.接受订单id
        Orders orders = ordersService.getById(orderId);
        //2.将orders的状态改为2，待派送
        orders.setStatus(2);
        //3.条件分页构造
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //4.如果他们的id一致
        lqw.eq(Orders::getNumber, orderId);
        //5.修改状态
        ordersService.update(orders, lqw);
        return "pay-success";
    }
}


